package com.feiyu.file.service.impl;

import com.feiyu.blog.entity.Picture;
import com.feiyu.blog.feign.PictureFeignClient;
import com.feiyu.common.constant.Constant;
import com.feiyu.common.constant.ResultCode;
import com.feiyu.common.exception.GlobalException;
import com.feiyu.file.service.FileService;
import com.feiyu.file.util.FileUtil;
import com.feiyu.resource.entity.Resource;
import com.feiyu.resource.feign.ResourceFeignClient;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadFileStream;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author tang ming
 * @since 2021/12/6 16:20
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private ResourceFeignClient resourceFeignClient;

    @Autowired
    private PictureFeignClient pictureFeignClient;

    @Override
    public StorePath upload(MultipartFile file) {
        StorePath storePath=null;
        try {
            storePath = storageClient.uploadFile(FileUtil.covert(file));
        }catch (Exception e){
            throw new GlobalException(ResultCode.FILE_UPLOAD_ERROR);
        }
        return storePath;
    }

    @Override
    public String uploadResource(MultipartFile file,Resource resource) {
        //如果有文档 保存到服务器
        if(file!=null){
            StorePath path = upload(file);
            //保存信息到数据库
            resource.setGroupName(path.getGroup());
            resource.setPath(path.getPath());
            resource.setName(file.getOriginalFilename());
            String fileName=file.getOriginalFilename();
            resource.setFileType(FileUtil.fileExtName(fileName));
            resource.setSize(file.getSize());
        }
        resourceFeignClient.save(resource);
        return Constant.DEFAULT_IMG_URL.concat(resource.getFullPath());
    }


    @Override
    public String uploadImage(MultipartFile file) {
        //保存到服务器
        StorePath path = upload(file);
        //保存信息到数据库
        Picture picture = new Picture();
        picture.setGroupName(path.getGroup());
        picture.setPath(path.getPath());
        picture.setName(file.getOriginalFilename());
        pictureFeignClient.save(picture);
        return Constant.DEFAULT_IMG_URL.concat(path.getFullPath());
    }

    /**
     * @param id
     * */
    @Override
    public boolean delete(long id,String type) {
        //判断是博客图片还是资源文件
        if ("resource".equals(type))
            return deleteResource(id);
        //否则删除博客图片
        return deleteImage(id);
    }

    private boolean deleteImage(long id){
        Picture detail = pictureFeignClient.detail(id).getData();
        if(detail==null||detail.getId()==null)
            throw new GlobalException(ResultCode.FILE_NOT_FOUND);
        storageClient.deleteFile(detail.getGroupName(), detail.getPath());
        pictureFeignClient.delete(id);
        return true;
    }

    private boolean deleteResource(long id){
        Resource detail = resourceFeignClient.detail(id).getData();
        if(detail==null||detail.getId()==null)
            throw new GlobalException(ResultCode.FILE_NOT_FOUND);
        storageClient.deleteFile(detail.getGroupName(), detail.getPath());
        resourceFeignClient.delete(id);
        return true;
    }


    @Override
    public void download(long id, HttpServletResponse response) {
        Resource data = resourceFeignClient.detail(id).getData();
        //如果资源不存在
        if(data==null||data.getId()==null)
            throw new GlobalException(ResultCode.FILE_NOT_FOUND);
        //否则传送文件
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(data.getName(), "UTF-8"));
            response.addHeader("Content-Length", "" + data.getSize());
            OutputStream os=response.getOutputStream();
            DownloadFileStream callback = new DownloadFileStream(os);
            storageClient.downloadFile(data.getGroupName(), data.getPath(), callback);
            os.close();
        }catch (Exception e){
            throw new GlobalException(ResultCode.FILE_DOWN_ERROR);
        }
    }

}
